package com.wnx.action;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.wnx.db.UserDao;
import com.wnx.entity.Users;

public class UpdateImgAction extends ActionSupport {
	 private File myFile;  
	 private int id;
	 
	    public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
		public File getMyFile() {  
	        return myFile;  
	    }  
	    public void setMyFile(File myFile) {  
	        this.myFile = myFile;  
	    }  
	  
	    private String myFileContentType;  
	  
	    private String myFileFileName;  
	  
	    private String destPath;  
	  
	    public String execute()  
	    {  
	         /* Copy file to a safe location */  
			destPath = ServletActionContext.getServletContext().getRealPath("/");
			File f = new File(destPath);
			f = new File(f.getParent(),"files/SecondaryMarket");
			destPath = f.getAbsolutePath(); 
			String name=null;
			String suffix = null;
	        try{  
	        	Users u = new Users();
	        	UserDao ud = new UserDao();
	        	name = UUID.randomUUID().toString().replaceAll("-", "");
	        	int index = myFileFileName.lastIndexOf(".");
	    		suffix = myFileFileName.substring(index, myFileFileName.length());
	            System.out.println("Src File name: " + myFile);  
	            System.out.println("Dst File name: " + name + suffix);  
	            File destFile  = new File(destPath, name + suffix);  
	            FileUtils.copyFile(myFile, destFile);
	            u.setId(this.id);
	            u.setImages("/files/SecondaryMarket/"+name+suffix);
	            ud.UpdateUserImgById(u);
	            
	        }catch(IOException e){  
	            e.printStackTrace();  
	            return ERROR;  
	        }  
	        Users ui =(Users) ActionContext.getContext().getSession().get("user");
	        ui.setImages("/files/SecondaryMarket/"+name+suffix);
	        ActionContext.getContext().getSession().put("user", ui);
	        return SUCCESS;  
	    }  
	  
	  
	    public String getMyFileContentType() {  
	        return myFileContentType;  
	    }  
	    public void setMyFileContentType(String myFileContentType) {  
	        this.myFileContentType = myFileContentType;  
	    }  
	    public String getMyFileFileName() {  
	        return myFileFileName;  
	    }  
	    public void setMyFileFileName(String myFileFileName) {  
	        this.myFileFileName = myFileFileName;  
	    }  
}
